/**
 * @Description: api 多节点控制，支持同一个请求，短时间重复的过滤
 */
import axios from "axios";
import qs from "qs";
import md5 from "md5";
import config from "@/config";
import Cookies from "js-cookie";
import { TOKEN_KEY } from "@/libs/util";

//发送请求的管理，同一请求在没有返回的情况下或者超时返回，不能反复请求
let requestManagement = {};

//API 全局配置
axios.defaults.baseURL = config.baseURL;
axios.defaults.timeout = 60000;
axios.defaults.withCredentials = true;
axios.defaults.transformRequest = [
  function(data, headers) {
    //return a string or an axios of Buffer, ArrayBuffer,FormData or Stream
    //return JSON.stringify(data);
    return qs.stringify(data);
    //return data;
  }
];

//请求拦截器
axios.interceptors.request.use(
  function(config) {
    //console.log("request", config);
    //config = requestUrl(config);
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);

//返回拦截器
axios.interceptors.response.use(
  function(response) {
    //console.log("response", response);
    //responseUrl(response.config);
    return response;
  },
  function(error) {
    return Promise.reject(error);
  }
);

/*
 * 拦截相同带参数的API，在第一个API没有回来前，后面都会被忽略
 */
function requestUrl(config) {
  let strData = "";
  if (config.data) {
    strData = JSON.stringify(config.data);
  }
  let requestId = md5(config.url + strData);
  if (requestManagement[requestId]) {
    return Promise.reject("该请求被取消,监测到API重复请求,请检查！");
  } else {
    requestManagement[requestId] = { createTime: new Date() };
  }
  config.requestId = requestId;
  return config;
}

//响应后，删除请求
function responseUrl(config) {
  if (requestManagement[config.requestId]) {
    delete requestManagement[config.requestId];
  }
}

//axios请求封装
export const request = function(data) {
  return new Promise((resolve, reject) => {
    //console.log(data);
    axios(data)
      .then(function(response) {
        let { data } = response;
        if (data.code !== 200) {
          if (data.code === 401) {
            Cookies.remove(TOKEN_KEY);
            console.log("没有权限,请登录后使用！");
            setTimeout(function() {
              window.location.href = "/";
            }, 2000);
          } else {
            if (data.msg) {
              console.log({
                duration: 2000,
                message: data.msg
              });
            } else {
              console.log("服务内部错误");
            }
          }
          return false;
        }
        resolve(data);
      })
      .catch(function(error) {
        console.log("Request error:", data.url, error);
        reject(error);
      });
  });
};

/****************************** 基础平台 通用api **************************/
//API login
export const login = obj => {
  let requestData = {
    method: "post",
    url: "login",
    data: obj
  };
  return request(requestData);
};

//API logout
export const logout = obj => {
  let requestData = {
    method: "get",
    url: "logout"
  };
  return request(requestData);
};

//API editPW
export const editPW = obj => {
  let requestData = {
    method: "POST",
    url: "Modify/CModifyPass",
    params: obj
  };
  return request(requestData);
};
